/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, { useEffect } from 'react';
import type { PropsWithChildren } from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Platform,
  ToastAndroid,
  TouchableOpacity,
  DeviceEventEmitter,
  NativeModules,
  PermissionsAndroid,
  Image,
} from 'react-native';
import { PersistGate } from 'redux-persist/integration/react';
const { HKVisionDeviceModule } = NativeModules;
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { Provider } from 'react-redux';
import { TopView, Theme } from 'teaset';
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './app/utils/RootNavigation';
import { createStackNavigator } from '@react-navigation/stack';
import MainScreen from './app/screens/MainScreen';
import { persistor, store } from './app/store/store.ts';

import { widthPercentageToDP } from 'react-native-responsive-hook';
import moment from 'moment';
import LogScreen from './app/screens/LogScreen';
import LoginScreen from './app/screens/LoginScreen';
import ClassroomScreen from './app/screens/ClassroomScreen.tsx';
import ReviewScreen from './app/screens/ReviewScreen.tsx';
import DeviceFixScreen from './app/screens/DeviceFixScreen.tsx';
import ReserveScreen from './app/screens/ReserveScreen.tsx';
import WebviewScreen from './app/screens/WebviewScreen.tsx';
import RoomsiteScreen from './app/screens/RoomsiteScreen.tsx';
import DeviceInfo from 'react-native-device-info';
import { Dirs } from 'react-native-file-access';
import ModalViewUtil from './app/components/ModalViewUtil.tsx';
import VideoScreen from './app/screens/VideoScreen.tsx';


const Stack = createStackNavigator();
function App(): React.JSX.Element {

  useEffect(() => {
    HKVisionDeviceModule && HKVisionDeviceModule.login('dev', '192.168.31.64', '8000', 'admin', 'Ccenrun2014!').then(res => {
      ToastAndroid.show('登录成功', ToastAndroid.SHORT);
    }).catch((error: any) => {
      console.log(error);
      ToastAndroid.show('登录失败', ToastAndroid.SHORT);
    });
    return () => {
      HKVisionDeviceModule && HKVisionDeviceModule.logout();
    };
  }, []);


  const headerRight = () => {
    return (
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity onPress={async () => {

          const permissions = [
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          ];
          const grantedPermissions = await PermissionsAndroid.requestMultiple(
            permissions,
          );
          if (
            grantedPermissions[
            PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
            ] === 'granted' &&
            grantedPermissions[
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
            ] === 'granted'
          ) {
            const date = moment().format('YYYY-MM-DDHH:mm:ss');
            // 截图
            // 创建一个临时图片文件地址，用于保存截图
            const tempPath = `${Dirs.CacheDir}/${DeviceInfo.getUniqueIdSync()
              }_${date}.png`;
            // 截图
            HKVisionDeviceModule && HKVisionDeviceModule.snap(tempPath, 1, 9, 1920 * 1080).then(() => {
              console.log('tempPath:', tempPath);
              ToastAndroid.show('截图成功' + tempPath, ToastAndroid.SHORT);
              ModalViewUtil.showFromCenter(<View style={{ width: 320, height: 800 }}>
                <Image source={{ uri: 'file://' + tempPath }} style={{ width: '100%', height: '100%' }} resizeMode="contain" />
              </View>);
            }).catch(error => {
              console.log(error);
              ToastAndroid.show('截图失败', ToastAndroid.SHORT);
            });
            // rtsp://admin:Ccenrun2014!@36.159.239.4:554/h264/1/main/av_stream
          }
          else {
            ToastAndroid.show('权限不足', ToastAndroid.SHORT);
          }
        }}>
          <Text
            style={{
              color: 'white',
              fontSize: widthPercentageToDP(4),
              paddingRight: widthPercentageToDP(1),
            }}>
            抓拍
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  const headerStyle = {
    headerStyle: {
      backgroundColor: 'rgb(10, 183, 139)',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
      fontWeight: 'bold',
    },
    headerTitleAlign: 'center',
  };

  return (
    <SafeAreaProvider>
      <GestureHandlerRootView style={{ height: '100%', width: '100%' }}>
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <TopView style={{ height: '100%', width: '100%' }}>
              <NavigationContainer ref={navigationRef}>
                <Stack.Navigator>
                  <Stack.Screen
                    name="MainScreen"
                    options={{
                      ...headerStyle,
                      title: '首页',
                      headerRight,
                    }}
                    component={MainScreen}
                  />
                  <Stack.Screen
                    name="ClassroomScreen"
                    options={{
                      ...headerStyle,

                    }}
                    component={ClassroomScreen}
                  />
                  <Stack.Screen
                    name="ReviewScreen"
                    options={{
                      ...headerStyle,
                      title: '预约审核',
                    }}
                    component={ReviewScreen}
                  />
                  <Stack.Screen
                    name="DeviceFixScreen"
                    options={{
                      ...headerStyle,
                      title: '报修',
                    }}
                    component={DeviceFixScreen}
                  />
                  <Stack.Screen
                    name="ReserveScreen"
                    options={{
                      ...headerStyle,
                      title: '预约查看',
                    }}
                    component={ReserveScreen}
                  />
                  <Stack.Screen
                    name="RoomsiteScreen"
                    options={{
                      ...headerStyle,
                      title: '座位管理',
                    }}
                    component={RoomsiteScreen}
                  />
                  <Stack.Screen
                    name="WebviewScreen"
                    options={{
                      ...headerStyle,
                      title: '',
                    }}
                    component={WebviewScreen}
                  />
                  <Stack.Screen
                    name="VideoScreen"
                    options={{
                      ...headerStyle,
                      title: '监控',
                    }}
                    component={VideoScreen}
                  />
                  <Stack.Screen
                    name="LoginScreen"
                    options={{
                      ...headerStyle,
                      title: '登录',
                    }}
                    component={LoginScreen}
                  />

                  <Stack.Screen
                    name="LogScreen"
                    options={{
                      headerShown: false,
                    }}
                    component={LogScreen}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </TopView>
          </PersistGate>
        </Provider>
      </GestureHandlerRootView>
    </SafeAreaProvider>
  );
}
export default App;
// 在根组件外加上PushyProvider后导出
// export default function Root() {
//   // 注意，在使用 PushyProvider 的当前组件中，无法直接调用 usePushy
//   // 只有当前组件的子组件才能调用 usePushy
//   return (
//     <PushyProvider client={pushyClient}>
//       {/* ↓ 整个应用的根组件放到PushyProvider中 */}
//       <App />
//     </PushyProvider>
//   );
// }
